package cn.felord.core.mongo.dao.impl;

import cn.felord.core.mongo.bean.FileEntity;
import cn.felord.core.mongo.dao.FileEntityDao;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * @author Dax
 * @since 22:39  2018/5/22
 */
@Component
public class FileEntityImpl implements FileEntityDao {
    private static final String FILE_COLLECTION = "FILE_ENTITIES";
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void save(FileEntity fileEntity) {
            mongoCollectionInitailizr();
        mongoTemplate.save(fileEntity, FILE_COLLECTION);
    }

    @Override
    public void saveBatch(Collection<FileEntity> fileEntities) {
        mongoCollectionInitailizr();
        mongoTemplate.insert(fileEntities, FILE_COLLECTION);
    }

    @Override
    public FileEntity findOne(String name) {
        Query query = new Query(Criteria.where("originalFilename").is(name));
        return mongoTemplate.findOne(query, FileEntity.class, FILE_COLLECTION);
    }

    private void mongoCollectionInitailizr() {
        if (!mongoTemplate.collectionExists(FILE_COLLECTION)) {
            mongoTemplate.createCollection(FILE_COLLECTION);
        }
    }
}
